// 保存当前需要收集的响应式函数
let activeReactiveFn = null

class Depend {
  constructor() {
    // 使用Set防止在函数里面多次取值触发多此调用
    this.reactiveFns = new Set()
  }
  // 订阅者
  depend() {
    if(activeReactiveFn) {
      this.reactiveFns.add(activeReactiveFn)
    }
  }
  // 发布者
  notiyf() {
    this.reactiveFns.forEach(fn => {
      fn()
    })
  }
}

// 创建一个weakMap保存所有对象
const weakMap = new WeakMap()

// 封装一个获取depend的函数
function getDepend(target,key) {
  let map = weakMap.get(target)
  if(!map) {
    map = new Map()
    weakMap.set(target,map)
  }
  // let depend = weakMap.get(target).get(key)
  let depend = map.get(key)
  if(!depend) {
    depend = new Depend
    // weakMap.get(target).set(key,depend)
    map.set(key,depend)
  }
  return depend
}

// 执行get操作时保存函数
function watchFn(fn) {
  activeReactiveFn = fn
  fn()
  activeReactiveFn = null
}

// 创造一个函数用来创建响应式对象
function reactiveObj (obj) {
  // 使用Proxy监听对象行为
  const objProxy = new Proxy(obj,{
    get:function(target,key,receiver) {
      const depend = getDepend(target,key)
      depend.depend()
      return Reflect.get(target,key,receiver)
    },
    set:function(target,key,newValue,receiver) {
      const depend = getDepend(target,key)
      Reflect.set(target,key,newValue,receiver)
      depend.notiyf()
    }
  })
  return objProxy
}